package cn.thornbird.orgsync.helper.token;

import cn.thornbird.orgsync.helper.NeteaseHelper;
import cn.thornbird.orgsync.model.certificate.NeteaseCertificate;
import cn.thornbird.orgsync.model.netease.Token;
import cn.thornbird.orgsync.util.JsonUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class NeteaseToken extends AccessToken<NeteaseCertificate> {

    public NeteaseToken(String certificateText) {
        super(certificateText);
        Map<String, Object> map = JsonUtil.parseMap(certificateText);
        NeteaseCertificate certificate = new NeteaseCertificate();
        certificate.setDomain(map.get("domain").toString());
        certificate.setAppId(map.get("appId").toString());
        certificate.setAuthCode(map.get("authCode").toString());
        certificate.setOrgOpenId(map.get("orgOpenId").toString());
        this.certificate = certificate;
    }

    @Override
    protected String acquireToken() {
        String token = INVALID_TOKEN_TEXT;
        NeteaseHelper helper = new NeteaseHelper();
        helper.initialize(null, certificateText);
        Map<String, Object> params = new HashMap<>();
        params.put("orgOpenId", certificate.getOrgOpenId());
        params.put("appId", certificate.getAppId());
        params.put("authCode", certificate.getAuthCode());
        Token result = helper.doPost(NeteaseHelper.ACQUIRE_TOKEN_PATH, params, null, Token.class);
        if (result != null && result.isSuccess()) {
            Date expiredTime = result.getData().getAccessTokenExpiredTime();
            token = result.getData().getAccessToken() + "," + (expiredTime.getTime() + EXPIRATION_DELTA);
        }
        return token;
    }

}
